<template>
	<view v-if="data != null">
		<view class="container">
		    <scroll-view scroll-y class="scrollable-content">
		      <view class="header">
		        <view class="header-content">
		          <view id="activityTimer" class="activity-timer">
		            <text id="activityStatus">火热进行中，剩余时间</text>
		            <view id="countdown">
		              <view v-for="(item, index) in countdownItems" :key="index" class="countdown-item">
		                <text class="countdown-number">{{ item.value }}</text>
		                <text class="countdown-label">{{ item.label }}</text>
		              </view>
		            </view>
		          </view>
		          <view class="logo-container">
		            <view v-if="data.images != ''" class="logo"><image :src="data.images" mode="aspectFit" class="img1"></image></view>
					<view v-else class="logo"></view>
		            <text class="project-name">{{data.title}}</text>
		          </view>
		          <view v-if="data.simple_desc_arr.length > 0" class="tag-container">
		            <text v-for="(tag, index) in data.simple_desc_arr" :key="index" class="tag">{{ tag }}</text>
		          </view>
		          <view v-if="data.metrics.length > 0" class="metrics">
		            <view v-for="(metric, index) in data.metrics" :key="index" class="metric-card">
		              <text class="metric-label">{{ metric.label }}</text>
		              <text :class="'metric-value metric-value-'+index">{{ metric.value }}</text>
		              <text v-if="metric.subLabel" class="metric-label">{{ metric.subLabel }}</text>
		            </view>
		          </view>
		        </view>
		      </view>
		
		      <view v-if="data.releaseSchedule.length > 0" class="section" id="publicSale">
		        <text class="section-title">发放周期</text>
		        <text class="section-title-sec">该项目活动将根据以下周期进行解锁</text>
		        <view class="timeline" id="releaseSchedule">
		          <view v-for="(item, index) in data.releaseSchedule" :key="index" class="timeline-item" :class="(index>5) ? timeline_item_hide : ''">
					  <view :class="['timeline-dot', item.status_str]"></view>
					  <view class="timeline-content">
						<text class="timeline-date">{{ item.date }}</text>
						<text :class="['timeline-status', item.status_str]">{{item.status}}</text>
					  </view>
					  <text class="timeline-percentage">{{item.bilv}}</text>
		          </view>
		        </view>
		        <view class="expand-button">
		          <button id="expandSchedule" class="primary-button" @click="toggleSchedule">{{ isScheduleExpanded ? '收起' : '展开更多' }}</button>
		        </view>
		      </view>
		
		      <view class="section" id="tokenContractAddress">
		        <text class="section-title">POC代币合约地址</text>
		        <view class="contract-section">
		          <view class="contract-address">
		            <text>POC Token Contract:</text>
		            <text class="address-text" id="contractAddress">{{ data.pay_address }}</text>
		          </view>
		          <button id="copyAddress" class="copy-button" @click="copyContractAddress">
		            <text>复制合约</text>
		          </button>
		        </view>
		        <view class="network-info">
		          <text>网络：</text>
		          <text class="network-name">Polygon (POL)</text>
		        </view>
		        <text class="description-text">您可以使用此合约地址在支持 Polygon 网络的钱包中添加 POC 代币。点击复制按钮即可复制地址。</text>
		      </view>
		
		      <view v-if="data.tradingInstructions.length > 0" class="section" id="tradingInstructions">
		        <text class="section-title">交易说明</text>
		        <view v-for="(instruction, index) in data.tradingInstructions" :key="index" class="trading-card">
		          <text class="trading-subtitle">{{ instruction.title }}</text>
		          <text class="trading-subtitle-desc">{{ instruction.content }}</text>
		          <view v-if="instruction.feeTable" class="fee-table">
		            <view v-for="(fee, feeIndex) in instruction.feeTable" :key="feeIndex" class="fee-row">
		              <text class="fee-row-desc">{{ fee.period }}</text>
		              <view>
		                <text class="buy-rate">买入: {{ fee.buyRate }}</text>
		                <text class="rate-separator">|</text>
		                <text class="sell-rate">卖出: {{ fee.sellRate }}</text>
		              </view>
		            </view>
		          </view>
		        </view>
		        <view class="warning-note">
		          <text>请注意：交易费率与分红可能会根据市场情况进行调整。请在交易前仔细查看最新的费率信息。</text>
		        </view>
		      </view>
		
		      <view v-if="data.benefits.length > 0" class="section" id="subscriptionBenefits">
		        <text class="section-title">认购权益</text>
		        <view id="benefitsList">
		          <view v-for="(benefit, index) in data.benefits" :key="index" class="benefit-card">
		            <text class="benefit-title">{{ benefit.title }}</text>
		            <text>{{ benefit.description }}</text>
		            <view class="required-amount">
		              <button class="required-amount-button">
		                <image :src="static_url_mini+'tt.png'" class="required-amount-icon" />
		                <text>{{ benefit.requiredAmount }}</text>
		              </button>
		            </view>
		          </view>
		        </view>
		      </view>
		
		      <view v-if="data.subscriptionRecords.length > 0" class="section" id="subscriptionRecords">
		        <text class="section-title">认购记录</text>
		        <view class="subscription-table">
		          <view class="table-header">
		            <text class="t1">地址</text>
		            <text class="t2">金额</text>
		            <text class="t3">时间</text>
		          </view>
		          <view id="subscriptionTable">
		            <view v-for="(record, index) in data.subscriptionRecords" :key="index" class="table-row">
		              <text class="t1">{{ record.address }}</text>
		              <text class="t2">{{ record.amount }}</text>
		              <text class="t3">{{ record.time }}</text>
		            </view>
		          </view>
		        </view>
		      </view>
		
		      <view v-if="data.conditions.length > 0" class="section" id="participationConditions">
		        <text class="section-title">参与条件</text>
		        <view id="conditionsList">
		          <view v-for="(condition, index) in data.conditions" :key="index" class="condition-card">
		            <text class="condition-title">{{ condition.title }}</text>
		            <text :class="['condition-status', condition.status]">
		              {{condition.status_str}}
		            </text>
		            <button v-if="condition.action === 'bindPIWallet' && condition.status === 'incomplete'" 
		                    class="primary-button bind-wallet-btn" :data-value="'/pages/fcc/bang/qianming/qianming'" @tap="url_event" style="margin-right:0;margin-left:0;">
		              {{ condition.title }}
		            </button>
					<button v-if="condition.action === 'bindPIWallet' && condition.status === 'completed'"
					        class="primary-button bind-wallet-btn" :data-value="'/pages/fcc/bang/qianming/qianming'" @tap="url_event" style="margin-right:0;margin-left:0;">
					  修改钱包
					</button>
					<button v-if="condition.action === 'bindEmail' && condition.status === 'incomplete'"
					        class="primary-button bind-wallet-btn" :data-value="'/pages/fcc/user-info/bind/bind?opt_form=email'" @tap="url_event" style="margin-right:0;margin-left:0;">
					  {{ condition.title }}
					</button>
		          </view>
		        </view>
		      </view>
		
		      <view v-if="data.guize.length > 0" class="section" id="activityRules">
		        <text class="section-title">活动规则</text>
		        <view id="rulesList" class="rules-list">
		          <view v-for="(rule, index) in data.guize" :key="index" class="rule-item">
		            <text>{{ rule }}</text>
		          </view>
		        </view>
		      </view>
		
		      <view class="section" id="projectDetails">
		        <text class="section-title">项目详情</text>
		        <view v-if="(data.content_web || null) != null"><mp-html :content="data.content_web" /></view>
		        <view v-if="data.socialLinks.length > 0" class="social-links">
		          <view v-for="(link, index) in data.socialLinks" :key="index" class="social-button" :data-value="link.url" data-type="0" @tap="navigation_event">
					<image :src="link.icon" class="icon" />
		            <text>{{ link.title }}</text>
		          </view>
		        </view>
		      </view>
		
		      <view v-if="data.video != ''" class="section" id="projectVideo">
		        <text class="section-title">项目视频介绍</text>
		        <view class="video-container">
		          <video :src="data.video" controls></video>
		        </view>
		        <text>观看我们的项目介绍视频，深入了解 POC 项目的愿景、技术创新和未来规划。</text>
		      </view>
		
		      <view v-if="data.tokenAllocations.length > 0" class="section" id="tokenAllocation">
		        <text class="section-title">代币分配</text>
		        <view class="allocation-grid" id="allocationList">
		          <view v-for="(allocation, index) in data.tokenAllocations" :key="index" class="allocation-item">
		            <text class="allocation-category">{{ allocation.category }}</text>
		            <text class="allocation-percentage">{{ allocation.percentage }}%</text>
		            <view class="allocation-bar">
		              <view class="allocation-progress" :style="{ width: allocation.percentage + '%' }"></view>
		            </view>
		          </view>
		        </view>
		      </view>
		
		      <view v-if="data.team_list.length > 0" class="section" id="projectTeam">
		        <text class="section-title">项目团队</text>
		        <view class="team-grid" id="teamList">
		          <view v-for="(member, index) in data.team_list" :key="index" class="team-member">
		            <image v-if="member.cover != ''" :src="member.cover" class="member-avatar" />
					<image v-else :src="static_url_mini+'touxiang.png'" class="member-avatar" />
		            <text class="member-name">{{ member.title }}</text>
		            <text class="member-role">{{ member.describe }}</text>
		            <view class="member-description"><mp-html :content="member.content" /></view>
		          </view>
		        </view>
		      </view>
		
		      <view v-if="data.xianlu_list.length > 0" class="section" id="projectRoadmap">
		        <text class="section-title">项目路线图</text>
		        <view id="roadmapList">
		          <view v-for="(item, index) in data.xianlu_list" :key="index" class="roadmap-item">
		            <text class="roadmap-quarter">{{ item.describe }}</text>
		            <text class="roadmap-milestone">{{ item.title }}</text>
					<view class="roadmap-details"><mp-html :content="item.content" /></view>
		          </view>
		        </view>
		      </view>
		    </scroll-view>
		
		    <view class="bottom-nav">
		      <button id="purchaseBtn" class="nav-button purchaseBtn" @click="openPurchaseModal">立即参与认购</button>
		      <button id="mySubscriptionsBtn" class="nav-button mySubscriptionsBtn" @click="openMySubscriptionsModal">我的认购</button>
		      <button id="referralRewardsBtn" class="nav-button referralRewardsBtn" @click="openReferralRewardsModal">推荐返利</button>
		    </view>
		
		    <!-- Modals -->
			<component-popup :propShow="purchaseModal" @onclose="closepurchaseModal">
		      <view class="modal-content">
		        <text class="modal-title">代币认购</text>
		        <view class="token-info">
		          <text class="info-title">代币信息:</text>
		          <text>名称: {{data.coin_name}}</text>
		          <text>符号: {{data.coin_mark}}</text>
		          <text>认购支付币种: {{data.buy_coin_type}}</text>
		        </view>
		        <form @submit="submitPurchase">
		          <view v-if="data.purchaseOptions != null" class="radio-options-container">
					  <radio-group @change="yxonclick">
					  	<label v-for="(option, index) in data.purchaseOptions" :key="index" class="radio-option">
					  		<radio :value="option.price" color="#09bb07" name="amount"  />{{option.label}}
					  	</label>
					  </radio-group>
		          </view>
		          <button form-type="submit" class="submit-purchase">提交认购</button>
		        </form>
		      </view>
		    </component-popup>
			
			<component-popup :propShow="MySubscriptionsModal" @onclose="closeMySubscriptionsModal">
		      <view class="modal-content">
		        <text class="modal-title">我的认购</text>
		        <view v-if="order_list.length > 0" id="subscriptionsList" class="scrollable-container">
		          <view v-for="(subscription, index) in order_list" :key="index" class="subscription-card">
		            <view class="subscription-header">
		              <text>订单号: {{ subscription.order_no }}</text>
		              <text :class="['status-badge', 'status-' + (subscription.status === 4 ? 'completed' : 'processing')]">
		                {{ subscription.status_name}}
		              </text>
		            </view>
		            <text>日期: {{ subscription.add_time }}</text>
		            <text>认购数量: {{ subscription.buy_value }} {{ subscription.goods_coin_mark }}</text>
		            <text>认购金额: {{subscription.currency_data.currency_symbol}} {{ subscription.price }}</text>
		            <text>PI用户名: {{ subscription.piuser }}</text>
		            <text>钱包地址: {{ subscription.wallet_address_view }}</text>
		          </view>
		        </view>
		      </view>
		    </component-popup>
		
			<component-popup :propShow="ReferralRewardsModal" @onclose="closeReferralRewardsModal">
		      <view class="modal-content">
		        <text class="modal-title">推荐返利</text>
		        <view class="referral-info">
		          <text class="info-title">推荐信息</text>
		          <view>{{data.fanli_desc}}</view>
		          <view>当前返利比例: <text class="reward-rate">{{data.fanli_bili}}%</text></view>
		          <view class="referral-link-container">
		            <input type="text" class="referral-link" id="referralLink" :value="referralLink" disabled />
		            <button class="copy-button" @click="copyReferralLink">复制</button>
		          </view>
		          <text class="referrer-info">您的推荐人: <text id="referrerName">{{ referrerName }}</text></text>
		        </view>
		        <view class="referral-rewards-section">
		          <text class="section-title">返利记录</text>
		          <view v-if="record_list.length > 0" id="referralRewardsList" class="scrollable-container">
		            <view v-for="(reward, index) in record_list" :key="index" class="subscription-card">
		              <view class="subscription-header">
		                <text>返利ID: {{ reward.id }}</text>
		                <text :class="['status-badge', 'status-' + (reward.status == 1 ? 'completed' : 'processing')]">
		                  {{ reward.status === 1 ? '已发放' : '处理中' }}
		                </text>
		              </view>
		              <text>日期: {{ reward.add_time }}</text>
		              <text>返利金额: {{ reward.money }} {{ reward.coin_mark }}</text>
		              <text>我推荐的用户: {{ reward.user.user_name_view }}</text>
		              <text>返利钱包地址: {{ reward.wallet_address_view }}</text>
		            </view>
		          </view>
		        </view>
		      </view>
		    </component-popup>
			
			<component-popup :propShow="confirmPurchaseModal" @onclose="closeconfirmPurchaseModal">
		      <view class="modal-content">
		        <text class="modal-title">确认认购信息</text>
		        <view>请提供您的PI用户名以完成认购</view>
		
		        <view class="form-group">
		          <text class="form-label">Pi 用户名</text>
		          <input 
		            type="text" 
		            v-model="piUsername"
		            placeholder="请输入您的Pi用户名"
		            class="form-input" @blur="yxblur" @confirm="yxblur" data-name="piUsername"
		          />
		        </view>
		
		        <!--<view class="form-group">
		          <text class="form-label">以太坊地址或Polygon地址</text>
		          <input 
		            type="text" 
		            v-model="walletAddress"
		            placeholder="0x... (以太坊或Polygon地址)"
		            class="form-input" @blur="yxblur" @confirm="yxblur" data-name="walletAddress" 
		          />
		        </view>-->
		
		        <view class="purchase-info">
		          <view class="info-row">
		            <text>认购数量:</text>
		            <text>{{ confirmAmount }}</text>
		          </view>
		          <view class="info-row">
		            <text>支付金额:</text>
		            <text>{{ confirmPayment }}</text>
		          </view>
		        </view>
		
		        <button id="confirmPurchaseBtn" class="submit-purchase confirmPurchaseBtn" @click="confirmPurchase" :loading="form_submit_loading" :disabled="form_submit_loading">确认并继续支付</button>
		      </view>
		    </component-popup>
		</view>
		
		<!-- 支付弹窗 -->
		<component-payment  
		    :propCurrencySymbol="currency_symbol"
		    :propPayUrl="pay_url"
		    :propQrcodeUrl="qrcode_url"
		    propPayDataKey="ids"
			:diyTheme="diytheme"
		    :propPaymentList="payment_list"
		    :propTempPayValue="temp_pay_value"
		    :propPayPrice="pay_price"
		    :propPaymentId="payment_id"
		    :propIsRedirectTo="true"
		    :propToFailPage="to_fail_page"
		    :propToAppointPage="to_appoint_page"
		    :propIsShowPayment="is_show_payment_popup"
		    @close-payment-popup="payment_popup_event_close"
		></component-payment>
	</view>
</template>

<script>
	const app = getApp();
	import componentNoData from '@/components/no-data/no-data';
	import componentPopup from "@/components/popup/popup";
	import componentPayment from '@/components/payment/payment';
	var static_url_mini = app.globalData.get_static_url('pisending', true);

export default {
  data() {
      return {
		  static_url_mini: static_url_mini,
		  data_list_loding_status: 1,
		  data_list_loding_msg: '',
		  data: null,
		  data_is_loading: 0,
		  purchaseModal: false,
		  MySubscriptionsModal: false,
		  ReferralRewardsModal: false,
		  timeline_item_hide: 'timeline-item-hide',
		  share_info: null,
		  selectedAmount: 0,
		  confirmPurchaseModal: false,
		  form_submit_loading: false,
		  currency_symbol: app.globalData.data.currency_symbol,
		  // 支付弹窗参数
		  pay_url: app.globalData.get_request_url('pay', 'index', 'pisending'),
		  qrcode_url: app.globalData.get_request_url('paycheck', 'index', 'pisending'),
		  payment_list: [],
		  temp_pay_value: '',
		  is_show_payment_popup: false,
		  pay_price: 0,
		  payment_id: 0,
		  diytheme: {
			  'main_color':'#9333EA',
			  'second_color':'#fac03d',
			  'ligth_color_1':'#feeaeb',
			  'ligth_color_2':'#feeaeb',
			  'ligth_color_deg':0,
			  'price_color':'#fa5d14',
		  },
		  order_list: [],
		  record_list: [],
		  // 支付失败跳转的页面
		  to_fail_page: '/pages/fcc/sending/index/index',
		  to_appoint_page: '/pages/fcc/sending/index/index',
        countdownItems: [
          { value: '00', label: '天' },
          { value: '00', label: '时' },
          { value: '00', label: '分' },
          { value: '00', label: '秒' }
        ],
        isScheduleExpanded: false,
        referralLink: '',
        referrerName: '',
        piUsername: '',
        walletAddress: '',
        confirmAmount: '',
        confirmPayment: ''
      }
    },
	components: {
	    componentNoData,
		componentPopup,
		componentPayment
	},
	onLoad(params) {
		this.setData({
			params: params,
		});
	},
	onShow() {
		app.globalData.page_event_onshow_handle();
		
		// 数据加载
		this.init();
	},
	// 下拉刷新
	onPullDownRefresh() {
	    this.get_data();
	},
    methods: {
		init(){
			var self = this;
			var user = app.globalData.get_user_info(this, "init");
			if (user != false) {
				this.get_data()
				.then(data=>{
					this.startCountdown(data.data.end_time_str);
					
					// 分享菜单处理
					app.globalData.page_share_handle();
				});
			} else {
				uni.stopPullDownRefresh();
						
				// 分享菜单处理
				app.globalData.page_share_handle();
			}
		},
		get_data() {
		    // 加载loding
		    uni.showLoading({
		        title: this.$t('common.loading_in_text'),
		    });
			return new Promise((resolve, reject) => {
				uni.request({
					url: app.globalData.get_request_url('detail', 'index', 'pisending'),
					method: 'POST',
					data: this.params,
					dataType: 'json',
					success: (res) => {console.log(res.data);
						uni.hideLoading();
						if (res.data.code == 0) {
							var data = res.data.data;
							var udp = {
								data_base: data.base || null, 
								data: data.data || null,
								data_list_loding_status: 3,
								data_list_loding_msg: '',
								data_is_loading: 0,
								payment_list: data.payment_list,
								payment_id: data.default_payment_id || 0,
								order_list: data.order_list || [],
								referralLink: data.user_share_url,
								record_list: data.record_list || [],
								referrerName: data.referrer_name || '',
							};
							// 基础自定义分享
							var share_info = {
							    title: data.data.title,
							    kds: data.data.simple_desc,
							    desc: data.data.simple_desc,
							    path: '/pages/fcc/pisending/detail/detail',
							    query: 'id=' + data.data.id,
							    img: data.data.images,
							    video: data.data.video
							}
							udp['share_info'] = share_info;
							this.setData(udp);
							
							resolve(udp);
						} else {
							this.setData({
								data_list_loding_status: 0,
								data_list_loding_msg: res.data.msg,
								data_is_loading: 0,
							});
							app.globalData.showToast(res.data.msg);
							
							reject(res.data.msg);
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
						this.setData({
							data_list_loding_status: 2,
							data_list_loding_msg: this.$t('common.internet_error_tips'),
							data_is_loading: 0,
						});
						app.globalData.showToast(this.$t('common.internet_error_tips'));
						
						reject(this.$t('common.internet_error_tips'));
					},
				});
			});
		},
		// url事件
		url_event(e) {
		    app.globalData.url_event(e);
		},
		navigation_event(e) {
		    app.globalData.operation_event(e);
		},
      toggleSchedule() {
        this.isScheduleExpanded = !this.isScheduleExpanded;
        // 实现展开/收起逻辑
		if(this.isScheduleExpanded)
		{
			this.setData({
				timeline_item_hide: ''
			});
		}else{
			this.setData({
				timeline_item_hide: 'timeline-item-hide'
			});
		}
      },
      copyContractAddress() {
        uni.setClipboardData({
          data: this.data.pay_address,
          success: () => {
            uni.showToast({ title: '合约地址已复制到剪贴板！', icon: 'success' });
          }
        });
      },
      openPurchaseModal() {
        this.setData({
			purchaseModal: true,
		});
      },
	  closepurchaseModal() {
        this.setData({
			purchaseModal: false,
		});
      },
      openMySubscriptionsModal() {
        this.setData({
        	MySubscriptionsModal: true,
        });
      },
	  closeMySubscriptionsModal() {
	    this.setData({
	    	MySubscriptionsModal: false,
	    });
	  },
      openReferralRewardsModal() {
        this.setData({
        	ReferralRewardsModal: true,
        });
      },
	  closeReferralRewardsModal() {
	    this.setData({
	    	ReferralRewardsModal: false,
	    });
	  },
	  // 单选多选
	  yxonclick(e){
	  	var value = e.detail.value;
	  	this.setData({
			selectedAmount: value
		});
	  },
      submitPurchase(e) {console.log(e);
        const selectedAmount = this.selectedAmount;
        if (selectedAmount) {
          // 更新确认模态框中的数据
          this.updateConfirmationData(selectedAmount);
		  this.setData({
		  	purchaseModal: false,
			confirmPurchaseModal: true,
		  });
        } else {
          uni.showToast({ title: '请选择认购金额！', icon: 'none' });
        }
      },
	  closeconfirmPurchaseModal() {
	    this.setData({
	    	confirmPurchaseModal: false,
	    });
	  },
      updateConfirmationData(amount) {
        const amountMap = this.data.purchaseOptions;
        this.confirmAmount = amountMap[amount].value+' '+this.data.coin_mark;
        this.confirmPayment = amountMap[amount].price+' '+this.data.buy_coin_type;
      },
      copyReferralLink() {
        uni.setClipboardData({
          data: this.referralLink,
          success: () => {
            uni.showToast({ title: '推荐链接已复制到剪贴板！', icon: 'success' });
          }
        });
      },
	  yxblur(e){console.log(e);
	  	var value = e.detail.value;
		var input_name = e.currentTarget.dataset.name;
	  	if(value != ''){
	  		if(input_name == 'piUsername')
			{
				this.piUsername = value;
			}
			if(input_name == 'walletAddress')
			{
				this.walletAddress = value;
			}
	  	}
	  },
      confirmPurchase() {
		  const conditions = this.data.conditions;
		  var jixu = true;
		  for (var i in conditions) {
			  
			  if(conditions[i].action === 'bindEmail' && conditions[i].status === 'incomplete')
			  {
				  jixu = false;
				  app.globalData.showToast('请先绑定邮箱');
				  break;
				  return;
			  }
			  if(conditions[i].action === 'bindPIWallet' && conditions[i].status === 'incomplete')
			  {
				  jixu = false;
				app.globalData.showToast('请先在参与条件中完成绑定钱包地址');
				break;
				return;
			  }
			  if(conditions[i].action === 'bindPIWallet' && conditions[i].status === 'completed')
			  {
			  	this.walletAddress = conditions[i].piqianbao;
			  }
		  }
		  if(!jixu)
		  {
			  return;
		  }
		const amountMap = this.data.purchaseOptions;
		var form_data = {};
		form_data['price'] = this.selectedAmount;// 购买价
		form_data['value'] = amountMap[this.selectedAmount].value;// 认购的数量
		form_data['label'] = amountMap[this.selectedAmount].label;// 购买结果-商品名称
		form_data['piusername'] = this.piUsername;// pi用户名
		form_data['walletaddress'] = this.walletAddress;// 钱包地址
		form_data['id'] = this.params.id || 0;// 商品ID
		console.log(form_data);
		// 数据验证
		var validation = [
		    { fields: 'piusername', msg: 'PI用户名不能为空' },
			{ fields: 'walletaddress', msg: '请先绑定PI钱包' },
		];
		if (app.globalData.fields_check(form_data, validation)) {
		    uni.showLoading({
		        title: this.$t('buy.buy.r79t77'),
		    });
		    this.setData({
		        form_submit_loading: true,
		    });
			var self = this;
		    // 网络请求
		    uni.request({
		        url: app.globalData.get_request_url('ordersave', 'index', 'pisending'),
		        method: 'POST',
		        data: form_data,
		        dataType: 'json',
		        success: (res) => {console.log(res.data);
		            uni.hideLoading();
		            if (res.data.code == 0) {
						// 重置表单+关闭弹窗
						this.setData({
							piUsername: '',
							walletAddress: '',
							confirmPurchaseModal: false,
						    form_submit_loading: false,
						});
						
						// 添加的时候，返回判断是否得到了订单ID
						if ((res.data.data || null) != null && res.data.data.order.status == 1) {
							uni.setStorageSync(app.globalData.data.cache_page_pay_key, { type: 1 });
							this.setData({
							    is_show_payment_popup: true,
							    pay_price: res.data.data.order.total_price,
							    temp_pay_value: res.data.data.order.id
							});
						} else {
							app.globalData.showToast(res.data.msg, 'success');
						    setTimeout(function () {
						    	self.init();
						    }, 2000);
						}
		            } else {
		                this.setData({
		                    form_submit_loading: false,
		                });
		                app.globalData.showToast(res.data.msg);
		            }
		        },
		        fail: () => {
		            uni.hideLoading();
		            this.setData({
		                form_submit_loading: false,
		            });
		            app.globalData.showToast(this.$t('common.internet_error_tips'));
		        },
		    });
		}
      },
	  
	  payment_popup_event_close() {
	      this.setData({
	          is_show_payment_popup: false,
				form_submit_loading: false
	      });
	  },
	  
      startCountdown(end_time) {//console.log(end_time);
        const endTime = new Date(end_time).getTime();//'2025-07-07T23:59:59'
        const timer = setInterval(() => {
          const now = new Date().getTime();
          const distance = endTime - now;
  
          if (distance < 0) {
            clearInterval(timer);
            this.countdownItems = [
              { value: '00', label: '天' },
              { value: '00', label: '时' },
              { value: '00', label: '分' },
              { value: '00', label: '秒' }
            ];
            return;
          }
  
          const days = Math.floor(distance / (1000 * 60 * 60 * 24));
          const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
          const seconds = Math.floor((distance % (1000 * 60)) / 1000);
  
          this.countdownItems = [
            { value: days.toString().padStart(2, '0'), label: '天' },
            { value: hours.toString().padStart(2, '0'), label: '时' },
            { value: minutes.toString().padStart(2, '0'), label: '分' },
            { value: seconds.toString().padStart(2, '0'), label: '秒' }
          ];
        }, 1000);
      }
    }
}
</script>

<style>
@import './detail.css';
</style>